package com.example.demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA 2023.
 * Description:
 * User: 故我
 * Date: 2023-11-25
 * Time: 13:59
 */
@RestController
@Slf4j
@RequestMapping("/imag")
public class ImagCodeController {

    public static LineCaptcha lineCaptcha;

    @RequestMapping("/getcode")
    public static void getCode(HttpServletResponse response) {
        // 将验证码进行输出
        RandomGenerator randomGenerator = new RandomGenerator("0123456789abcdefghijklmnopqrstuvwxyz", 4); // 生成一个6位数的验证码
        lineCaptcha = CaptchaUtil.createLineCaptcha(150, 45);//定义图形验证码的大小
        // 设置对应的报头格式
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");

        try {
            // 设置图形验证码的格式
            lineCaptcha.setGenerator(randomGenerator); //随机的
            // 输出到网络报头中
            lineCaptcha.write(response.getOutputStream());
            log.debug("生成的图片验证码为: " + lineCaptcha.getCode());
            // 关闭输出流
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
